import { Component, ElementRef, ViewChild, AfterViewInit, Directive, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, NgForm, NgModel } from '@angular/forms';
import { Md5 } from 'ts-md5';
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  // Constructor
  constructor(public http: HttpClient, private router: Router) {
    this.authForm = new FormGroup({
      'username': new FormControl(null, Validators.required),
      'password': new FormControl(null, [Validators.required, Validators.minLength(6)]),
      'confirmPassword': new FormControl(null)
    });
  }

  @ViewChild("verifyCanvas", { static: true })
  private readonly verifyCanvas!: ElementRef<HTMLCanvasElement>;
  authForm: FormGroup;
  authMode = 'Login';
  public ctx: any;

  change(para: any) {

    if (para == 'username') {
      let nameDom: any = document.getElementById('username');
      this.user.username = nameDom.value;
      if (this.user.username == '') {
        this.usernameEmpty = true;
      } else {
        this.usernameEmpty = false;
      }
    }

    if (para == 'password') {
      let nameDom: any = document.getElementById('password');
      this.user.password = nameDom.value;
      if (this.user.password == '') {
        this.pasEmpty = true;
      } else {
        this.short = false;
        this.pasEmpty = false;
      }
    }

    if (para == 'code') {
      let nameDom: any = document.getElementById('code');
      this.user.verifyCode = nameDom.value;
      if (this.user.verifyCode != '') {
        this.code = false;
      }
    }
    if (para == 'comformPas') {
      let nameDom: any = document.getElementById('confirmPassword');
      this.user.confirmPas = nameDom.value;
      if (this.user.confirmPas == '') {
        this.confirmPassword = true;
      } else {
        this.same = false;
        this.confirmPassword = false;
      }
    }

  }

  public user: any = {
    'username': '',
    'password': '',
    'verifyCode': '',
    'confirmPas': ''
  }
  public usernameEmpty: any = false;
  public pasEmpty: any = false;
  public code: any = false;
  public short: any = false;
  public confirmPassword: any = false;
  public same: any = false;
  public message: any = false;
  public type: any = 'success';
  public text: any = '登录成功';

  // Switch between Login and Signup modes
  onSwitchMode() {
    this.refresh();
    this.usernameEmpty = false;
    this.pasEmpty = false;
    this.code = false;
    this.short = false;
    this.confirmPassword = false;
    this.same = false;
    this.user.username = '';
    this.user.password = '';
    this.user.confirmPas = '';
    this.user.verifyCode = '';
    this.user.confirmPas = '';
    if (this.authMode === 'Login') {
      this.authMode = 'Signup';
    } else {
      this.authMode = 'Login';
    }
  }

  // Submit form
  onSubmit() {

    if (this.authMode == 'Login') {
      if (this.user.username == '') {
        this.usernameEmpty = true;
        return;
      }
      if (this.user.password == '') {
        this.pasEmpty = true;
        return;
      }
      if (!this.validate(this.user.verifyCode)) {
        this.code = true;
        return;
      }
      //加密
      this.user.password = Md5.hashStr(this.user.password);
      // 访问接口
      const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
      };

      var api = "http://124.221.112.204:3389/user/login";
      // var api_test = "http://127.0.0.1:8080/user/login";

      this.http.post(api, this.user, httpOptions).subscribe((response: any) => {
        if (response.code == 200) {
          sessionStorage.setItem('username', this.user.username);
          this.user.username = '';
          this.user.password = '';
          this.user.confirmPas = '';
          this.user.verifyCode = '';
          this.refresh();
          this.message = true;
          this.type = 'success';
          this.text = '登录成功';
          setTimeout(() => {
            this.message = false;

          }, 2000);
          // 设置token
          sessionStorage.setItem('token', response.data.token);

          // 存储id
          sessionStorage.setItem('userid', response.data.id);
          //console.log(response);

          // 跳转到首页
          if (response.data.model != null) {
            var f: any = document.getElementById('iframeId');
            // 触发子页面的监听事件
            f.contentWindow.postMessage({ model: response.data.model }, '*');
            f.contentWindow.postMessage({ color: response.data.color }, '*');
            f.contentWindow.postMessage({ username: sessionStorage.getItem("username") }, '*');

            sessionStorage.setItem("model", response.data.model);
            sessionStorage.setItem("color", response.data.color);
            setTimeout(() => {
              this.router.navigateByUrl('index');
            }, 500);

          } else {
            this.router.navigateByUrl('choose');
          }


        } else {
          this.message = true;
          this.type = 'failure';
          this.text = response.msg;
          setTimeout(() => {
            this.message = false;
          }, 2000);
          this.user.username = '';
          this.user.password = '';
          this.user.confirmPas = '';
          this.user.verifyCode = '';
        }
      });
    }

    if (this.authMode == 'Signup') {
      if (this.user.username == '') {
        this.usernameEmpty = true;
        return;
      }
      if (this.user.password == '') {
        this.pasEmpty = true;
        return;
      }
      if (this.user.password.length < 6) {
        this.short = true;
        return;
      }
      if (this.user.confirmPas == '') {
        this.confirmPassword = true;
        return;
      }
      if (this.user.confirmPas != this.user.password) {
        this.same = true;
        return;
      }
      if (!this.validate(this.user.verifyCode)) {
        this.code = true;
        return;
      }
      //加密
      this.user.confirmPas = this.user.password = Md5.hashStr(this.user.password);
      // 访问接口
      const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
      };

      var api = "http://124.221.112.204:3389/user/register";
      // var api_test = "http://127.0.0.1:8080/user/register";

      this.http.post(api, this.user, httpOptions).subscribe((response: any) => {
        if (response.code == 200) {
          this.refresh();
          this.message = true;
          this.type = 'success';
          this.text = '注册成功,即将跳转到登录页';
          setTimeout(() => {
            this.message = false;
            this.onSwitchMode();
          }, 2000);
        } else {
          this.user = {
            'username': '',
            'password': '',
            'verifyCode': '',
            'confirmPas': ''
          }
          this.message = true;
          this.type = 'failure';
          this.text = response.msg;
          setTimeout(() => {
            this.message = false;
          }, 2000);
        }
      });
    }

  }

  // 生成验证码
  codeLength = 4; // 设置验证码长度
  public options: any = {
    // 默认options参数值
    id: 'v_container', // 容器Id
    canvasId: 'verifyCanvas', // canvas的ID
    width: 100, // 默认canvas宽度
    height: 40, // 默认canvas高度
    type: 'blend', // 图形验证码默认类型blend:数字字母混合类型、number:纯数字、letter:纯字母
    code: '',
    numArr: [],
    letterArr: [],
  };

  ngOnInit() {
    this.ctx = this.verifyCanvas.nativeElement.getContext('2d');
    this.options.numArr = '0,1,2,3,4,5,6,7,8,9'.split(',');
    this.options.letterArr = this.getAllLetter();
    this.refresh();
  }

  // 生成验证码
  refresh() {
    this.options.code = '';
    this.ctx.textBaseline = 'middle';

    this.ctx.fillStyle = this.randomColor(180, 240);
    this.ctx.fillRect(0, 0, this.options.width, this.options.height);

    let txtArr = [];
    if (this.options.type === 'blend') {
      // 判断验证码类型
      txtArr = this.options.numArr.concat(this.options.letterArr);
    } else if (this.options.type === 'number') {
      txtArr = this.options.numArr;
    } else {
      txtArr = this.options.letterArr;
    }

    for (let i = 1; i <= this.codeLength; i++) {
      const txt = txtArr[this.randomNum(0, txtArr.length)];
      this.options.code += txt;
      this.ctx.font = this.randomNum(this.options.height / 2, this.options.height) + 'px SimHei'; // 随机生成字体大小
      this.ctx.fillStyle = this.randomColor(50, 160); // 随机生成字体颜色
      this.ctx.shadowOffsetX = this.randomNum(-3, 3);
      this.ctx.shadowOffsetY = this.randomNum(-3, 3);
      this.ctx.shadowBlur = this.randomNum(-3, 3);
      this.ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
      const x = (this.options.width / (this.codeLength + 1)) * i;
      const y = this.options.height / 2;
      const deg = this.randomNum(-30, 30);
      // 设置旋转角度和坐标原点
      this.ctx.translate(x, y);
      this.ctx.rotate((deg * Math.PI) / 180);
      this.ctx.fillText(txt, 0, 0);
      // 恢复旋转角度和坐标原点
      this.ctx.rotate((-deg * Math.PI) / 180);
      this.ctx.translate(-x, -y);
    }
    // 绘制干扰线
    // for (let i = 0; i < 2; i++) {
    //   this.ctx.strokeStyle = this.randomColor(40, 180);
    //   this.ctx.beginPath();
    //   this.ctx.moveTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height));
    //   this.ctx.lineTo(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height));
    //   this.ctx.stroke();
    // }
    // 绘制干扰点
    for (let i = 0; i < this.options.width / 2; i++) {
      this.ctx.fillStyle = this.randomColor(0, 255);
      this.ctx.beginPath();
      this.ctx.arc(this.randomNum(0, this.options.width), this.randomNum(0, this.options.height), 1, 0, 2 * Math.PI);
      this.ctx.fill();
    }
  }

  // 验证验证码
  validate(code: any) {
    const code1 = code.toLowerCase();
    const v_code = this.options.code.toLowerCase();
    // console.log(code1 + ' ---- ' + v_code);

    if (code1 === v_code) {
      return true;
    } else {
      this.refresh();
      return false;
    }
  }

  // 生成字母数组
  getAllLetter() {
    const letterStr =
      'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
    return letterStr.split(',');
  }

  // 生成一个随机数
  randomNum(min: any, max: any) {
    return Math.floor(Math.random() * (max - min) + min);
  }

  // 生成一个随机色
  randomColor(min: any, max: any) {
    const r = this.randomNum(min, max);
    const g = this.randomNum(min, max);
    const b = this.randomNum(min, max);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
  }
}
